package com.frkj.yuan.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.frkj.yuan.R;
import com.frkj.yuan.api.bean.UploadNichengMsgBean;
import com.frkj.yuan.api.category.UploadNichengMsgCategory;
import com.frkj.yuan.api.presenter.UploadNichengMsgPresenter;
import com.frkj.yuan.base.BaseActivity;
import com.frkj.yuan.dialog.OnUploadPicDialogClickListener;
import com.frkj.yuan.dialog.UploadPicDialog;
import com.frkj.yuan.entity.JsonBean;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.utils.CameraUtils;
import com.frkj.yuan.utils.FullScreenUtils;
import com.frkj.yuan.utils.IDCardValidateUtils;
import com.frkj.yuan.utils.SPUtils;
import com.frkj.yuan.utils.ToastUtil;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 作者：菲菲 on 2022/2/11 17:34
 * company：丰蓉信息科技有限公司
 */
public class UserPersonalActivity extends BaseActivity implements UploadNichengMsgCategory.View {
    @BindView(R.id.base_title)
    TextView mTitleMsg;
    @BindView(R.id.icon_personal)
    CircleImageView mIconImage;
    @BindView(R.id.address)
    TextView mSelectAddress;
    @BindView(R.id.nick_name)
    EditText mEditText;
    @BindView(R.id.address_detials)
    EditText mEditAddress;
    @BindView(R.id.edit_sfz)
    EditText mEditSfz;
    @BindView(R.id.editt_name)
    EditText mEditName;
    @BindView(R.id.edit_mobile_person)
    TextView mMobilePhone;
    private ArrayList<JsonBean> mPrivce = new ArrayList<>(); //省
    private ArrayList<ArrayList<String>> mCity = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> mAreas = new ArrayList<>();//区
    private UploadPicDialog dialog;
    private UploadNichengMsgPresenter mPresenter;
    private long mUserId;
    private String mIconPath, sfzhm, mNichengName, mToken, mUserName;
    @Override
    public int getLayoutId() {
        return R.layout.activity_person_view;
    }

    @Override
    public void initLayoutView() {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String regEx = "[\\[\\]]";
                Pattern pattern = Pattern.compile(regEx);
                Matcher matcher = pattern.matcher(source.toString());
                Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
                Matcher emojiMatcher = emoji.matcher(source);
                if (matcher.find() || emojiMatcher.find()|| source.equals(" ")|| source.toString().contentEquals("\n")) {
                    ToastUtil.showToastINFO(UserPersonalActivity.this,"禁止输入非法字符");
                    return "";
                } else {
                    return null;
                }
            }
        };
        InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(10);
        mEditText.setFilters(new InputFilter[]{filter, lengthFilter});
        mEditName.setFilters(new InputFilter[]{filter, lengthFilter});
        FullScreenUtils.getInstance().fullScreen(UserPersonalActivity.this, true);
        mTitleMsg.setText("个人设置");
        mPresenter = new UploadNichengMsgPresenter(this);
        SetPersenter(mPresenter);
        String mIconImageAvartar = getIntent().getStringExtra("iconImage");
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.error(R.drawable.head_icon)
                .circleCrop()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(UserPersonalActivity.this)
                .load(mIconImageAvartar)
                .apply(requestOptions)
                .into(mIconImage);
        String mNickName = getIntent().getStringExtra("nickName");
        String userName = getIntent().getStringExtra("name");
        String mSfzCardId = getIntent().getStringExtra("mSfzCardId");
        mEditSfz.setText(mSfzCardId);
        mEditName.setText(userName);
        mEditText.setText(mNickName);
        mMobilePhone.setText(getIntent().getStringExtra("mobile"));
        mToken = (String) SPUtils.get(UserPersonalActivity.this, ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = UserPersonalActivity.this.getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
    }

    @OnClick({R.id.base_back, R.id.relat_icon, R.id.address_person, R.id.submit_person})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finishWitchAnimation();
                break;
            case R.id.relat_icon:
                selectIconImageDialog();
                break;
//            case R.id.address_person:
//                BaseActivity.hideKeyBoard(this);
//                initJsonData();
//                initOptionPicker();
//                break;
            case R.id.submit_person:
                sfzhm = mEditSfz.getText().toString().trim();
                mNichengName = mEditText.getText().toString().trim();
                mUserName = mEditName.getText().toString().trim();
                if (sfzhm.equals("")) {
                    ToastUtil.showToastINFO(UserPersonalActivity.this, "请输入就诊人身份证号码");
                    return;
                } else {
                    try {
                        if (!IDCardValidateUtils.checkIdCardNum(sfzhm)) {
                            ToastUtil.showToastINFO(UserPersonalActivity.this, "身份证号码输入有误");
                            mEditSfz.setText("");
                            return;
                        } else {
                            mPresenter.uploadImageNicheng(mUserId, mToken, mUserName, sfzhm, mNichengName);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
//
//    //解析数据 （省市区三级联动）
//    private void initJsonData() {
//        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
//        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
//        /**
//         * 添加省份数据
//         *
//         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
//         * PickerView会通过getPickerViewText方法获取字符串显示出来。
//         */
//        mPrivce = jsonBean;
//        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
//            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
//            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）
//
//            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
//                String CityName = jsonBean.get(i).getCityList().get(c).getName();
//                CityList.add(CityName);//添加城市
//                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
//                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
//                if (jsonBean.get(i).getCityList().get(c).getArea() == null
//                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
//                    City_AreaList.add("");
//                } else {
//                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
//                }
//                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
//            }
//            /**
//             * 添加城市数据
//             */
//            mCity.add(CityList);
//            /**
//             * 添加地区数据
//             */
//            mAreas.add(Province_AreaList);
//        }
//    }
//
//    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
//        ArrayList<JsonBean> detail = new ArrayList<>();
//        try {
//            JSONArray data = new JSONArray(result);
//            Gson gson = new Gson();
//            for (int i = 0; i < data.length(); i++) {
//                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
//                detail.add(entity);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return detail;
//    }
//
//    private void initOptionPicker() {
//        /**
//         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
//         */
//        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                //返回的分别是三个级别的选中位置
//                mSelectAddress.setText(mPrivce.get(options1).getPickerViewText()
//                        + mCity.get(options1).get(options2)
//                        + mAreas.get(options1).get(options2).get(options3));
//                provStr = mPrivce.get(options1).getPickerViewText();
//                cityStr = mCity.get(options1).get(options2);
//                regionStr = mAreas.get(options1).get(options2).get(options3);
//            }
//        })
//                .setTitleText("城市选择")
//                .setCancelColor(Color.parseColor("#333333"))
//                .setTextColorCenter(Color.parseColor("#333333")) //设置选中项文字颜色
//                .setContentTextSize(16)
//                .build();
//        pvOptions.setPicker(mPrivce, mCity, mAreas);//三级选择器
//        pvOptions.show();
//    }

    /**
     * 拍照弹出窗口
     */
    private void selectIconImageDialog() {
        dialog = new UploadPicDialog(this, new OnUploadPicDialogClickListener() {
            // TODO: 2022/5/3 拍照
            @Override
            public void onPhoto(Dialog dialog) {
                // 权限申请
                if (ContextCompat.checkSelfPermission(UserPersonalActivity.this,
                        Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(UserPersonalActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 权限还没有授予，需要在这里写申请权限的代码
                    ActivityCompat.requestPermissions(UserPersonalActivity.this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 300);
                } else {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri imageUri = CameraUtils.getOutputMediaFileUri(UserPersonalActivity.this);
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    //Android7.0添加临时权限标记，此步千万别忘了
                    openCameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(openCameraIntent, 100);
                }

                dialog.dismiss();
            }

            // TODO: 2022/5/3 从相册选择图片
            @Override
            public Intent onPicture(Dialog dialog) {
                // 权限申请
                if (ContextCompat.checkSelfPermission(UserPersonalActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //权限还没有授予，需要在这里写申请权限的代码
                    ActivityCompat.requestPermissions(UserPersonalActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
                } else {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 200);
                }
                dialog.dismiss();
                return null;
            }

            @Override
            public void onCancel(Dialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            Bitmap originBitmap = CameraUtils.getBitmapWithRightRotation(CameraUtils.sCameraPath);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.error(R.drawable.head_icon)
                    .circleCrop()
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE);
            Glide.with(UserPersonalActivity.this)
                    .load(originBitmap)
                    .apply(requestOptions)
                    .into(mIconImage);
            mIconPath = CameraUtils.sCameraPath;
            mPresenter.uploadImage(mUserId, mToken, mIconPath);
        } else if (requestCode == 200) {
            if (data!=null){
                mIconPath = CameraUtils.getRealPathFromUri(UserPersonalActivity.this, data.getData());
                Bitmap originBitmap = CameraUtils.getBitmapWithRightRotation(mIconPath);
                RequestOptions requestOptions = new RequestOptions();
                requestOptions.error(R.drawable.head_icon)
                        .circleCrop()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE);
                Glide.with(UserPersonalActivity.this)
                        .load(originBitmap)
                        .apply(requestOptions)
                        .into(mIconImage);
                mPresenter.uploadImage(mUserId, mToken, mIconPath);
            }else {
                dialog.dismiss();
            }
        }
    }

    @Override
    public void uploadImage(UploadNichengMsgBean bean) {
        if (bean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            ToastUtil.showToastSUCCESS(UserPersonalActivity.this, "头像上传成功");
        } else {
            ToastUtil.showToastINFO(UserPersonalActivity.this, bean.getMsg());
        }
    }

    @Override
    public void uploadImageNicheng(UploadNichengMsgBean bean) {
        if (bean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            ToastUtil.showToastSUCCESS(UserPersonalActivity.this, "个人信息更新成功");
            Intent intent = new Intent();
            //把返回数据存入Intent
            intent.putExtra("nickName", bean.getData().getNickName());
            intent.putExtra("iconImage", bean.getData().getAvatar());
            mEditName.setHint("");
            mEditText.setHint("");
            //设置返回数据
            UserPersonalActivity.this.setResult(200, intent);//RESULT_OK为自定义常量
            //关闭Activity
            UserPersonalActivity.this.finish();
        } else {
            ToastUtil.showToastINFO(UserPersonalActivity.this, bean.getMsg());
        }
    }

    @Override
    public void SetPersenter(Object persenter) {
    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(UserPersonalActivity.this, mErrorMsg);
    }


}
